<?php

/**
 * Description of
 *
 * @author yuanjun.liu
 */
class User extends App {

    public $pageSize = 25;

    protected function getTableName() {
        return 'user';
    }

    protected function getPrimaryField() {
        return 'id';
    }

    public function showAdd() {
        $roles = Role::getAll();
        include $this->tpl('userAdd');
    }

    public function doAdd() {
        if ((!$email = (string) trim($_REQUEST['email'])) || preg_match("/[a-zA-Z]{1}[a-zA-Z0-9_]{5,}@[a-zA-Z0-9]{1,}\.[a-zA-Z]{1,3}/", $email, $matches))
            $this->redirect('javascript:history.back(-1);', '邮箱填写有误！', 2, 0);
        if (!$name = (string) trim($_REQUEST['name']))
            $this->redirect('javascript:history.back(-1);', '用户名必填！', 2, 0);
        if (!$passwd = (string) trim($_REQUEST['passwd']))
            $this->redirect('javascript:history.back(-1);', '没有设定初始密码！', 2, 0);
        if (!$role = (string) trim($_REQUEST['role'])) {
            $this->redirect('javascript:history.back(-1);', '没有选择用户组！', 2, 0);
        } else {
            $roleApp = new Role();
            if (!$roleInfo = $roleApp->find($role)) {
                $this->redirect('javascript:history.back(-1);', '用户组不存在！', 2, 0);
            }
        }
        if (!empty($_REQUEST['extended_role'])) {
            //不管旧版本，只兼容PHP5.3
            $extendedRole = array_filter($_REQUEST['extended_role'], function($v) {
                        return is_int($v) && $v && $v != $role;
                    });
        }
        if (!empty($_REQUEST['permission'])) {
            $extendedPermission = array_filter($_REQUEST['permission']);
        }
        $data = array(
            'email' => $email,
            'name' => $name,
            'passwd' => md5($passwd),
            'status' => 1,
            'pinyin' => pinyin($name),
            'mobile' => trim($_REQUEST['mobile']),
            'gender' => (int) $_REQUEST['gender'],
            'role' => $role,
            'role_name' => $roleInfo['name'],
            'extended_role' => serialize($extendedRole),
            'permission' => $extendedPermission,
            'create_time' => TS_NOW
        );
        if ($this->table()->insert($data)) {
            $this->redirect(jaUrl('user', 'list'), '帐号添加成功！正在跳回列表页..', 1, 2);
        } else {
            $this->redirect(jaUrl('user', 'list'), '帐号添加失败！错误信息如下:<br />' . $this->db->getError(), 2, 0);
        }
    }

    public function showEdit() {
        $id = (string) $_REQUEST['id'];
        ($detail = $this->find($id)) || jaError(6);
        $roles = Role::getAll();
        $detail['extended_role'] = (array)unserialize($detail['extended_role']);
        $detail['permission'] = (array)unserialize($detail['permission']);
        include $this->tpl('userEdit');
    }

    public function doEdit() {
        if (!$id = (int) trim($_REQUEST['id']))
            $this->redirect(jaUrl('user', 'list'), '没有指定ID！', 2, 0);
        if ((!$email = (string) trim($_REQUEST['email'])) || preg_match("/[a-zA-Z]{1}[a-zA-Z0-9_]{5,}@[a-zA-Z0-9]{1,}\.[a-zA-Z]{1,3}/", $email, $matches))
            $this->redirect('javascript:history.back(-1);', '邮箱填写有误！', 2, 0);
        if (!$name = (string) trim($_REQUEST['name']))
            $this->redirect('javascript:history.back(-1);', '用户名必填！', 2, 0);
        if (!$role = (string) trim($_REQUEST['role'])) {
            $this->redirect('javascript:history.back(-1);', '没有选择用户组！', 2, 0);
        } else {
            $roleApp = new Role();
            if (!$roleInfo = $roleApp->find($role)) {
                $this->redirect('javascript:history.back(-1);', '用户组不存在！', 2, 0);
            }
        }
        if (!empty($_REQUEST['extended_role'])) {
            //不管旧版本，只兼容PHP5.3
            $extendedRole = array_filter($_REQUEST['extended_role'], function($v) {
                        return is_int($v) && $v && $v != $role;
                    });
        }
        if (!empty($_REQUEST['permission'])) {
            $extendedPermission = array_filter($_REQUEST['permission']);
        }
        $data = array(
            'email' => $email,
            'name' => $name,
            'pinyin' => pinyin($name),
            'mobile' => trim($_REQUEST['mobile']),
            'gender' => (int) $_REQUEST['gender'],
            'role' => $role,
            'role_name' => $roleInfo['name'],
            'extended_role' => serialize($extendedRole),
            'permission' => $extendedPermission
        );
        if ($passwd = (string) trim($_REQUEST['passwd']))
            $data['passwd'] = md5($passwd);
        if ($this->table()->where(array($this->getPrimaryField(), 'eq', $id))->update($data)) {
            $this->redirect(jaUrl('user', 'list'), '更新成功！正在跳回列表页..', 1, 2);
        } else {
            $this->redirect(jaUrl('user', 'list'), '操作失败！错误信息如下:<br />' . $this->db->getError(), 2, 0);
        }
    }

    public function doDelete() {
        ($id = (string) trim($_REQUEST['id'])) || jaError(6);
        if ($this->delete($id)) {
            $this->redirect(jaUrl('user', 'list'), '删除成功！正在跳回列表页..', 1, 2);
        } else {
            $this->redirect(jaUrl('user', 'list'), '操作失败！错误信息如下:<br />' . $this->db->getError(), 2, 0);
        }
    }

    public function doActive() {
        $id = (int) $_REQUEST['id'];
        if (false !== $this->table()->where(array($this->getPrimaryField(), 'eq', $id))->update(array('status' => 1))) {
            $this->redirect(jaUrl('user', 'list'), '激活成功！正在跳回列表页..', 1, 2);
        } else {
            $this->redirect(jaUrl('user', 'list'), '操作失败！错误信息如下:<br />' . $this->db->getError(), 2, 0);
        }
    }

    public function doLock() {
        $id = (int) $_REQUEST['id'];
        $status = (int) $_REQUEST['status'];
        $status = $status == 1 ? 1 : 2;
        if (false !== $this->table()->where(array($this->getPrimaryField(), 'eq', $id))->update(array('status' => $status))) {
            $this->redirect(jaUrl('user', 'list'), '更新成功！正在跳回列表页..', 1, 2);
        } else {
            $this->redirect(jaUrl('user', 'list'), '操作失败！错误信息如下:<br />' . $this->db->getError(), 2, 0);
        }
    }

    public function showList() {
        (isset($_REQUEST['page']) && $page = (int) $_REQUEST['page']) || ($page = 1);
        $total = $this->count();
        $list = $this->table()->limit(($page - 1) * $this->pageSize . ',' . $this->pageSize)->order('`create_time` DESC')->select();
        if (!empty($list))
            $this->processList($list);
        $showPages = showPages($total, $this->pageSize);
        include $this->tpl('userList');
    }

    protected function processList(&$list) {
        foreach ($list as &$val) {
            $val['gender'] = intval($val['gender']);
            $val['gender'] = $val['gender'] === 1 ? '男' : ($val['gender'] === 2 ? '女' : '未知');
            $val['last_visit'] = $val['last_visit'] ? date('Y-m-d', $val['last_visit']) : '从未';
            $val['last_ip'] = $val['last_ip'] ? $val['last_ip'] : '从未';
            $val['status'] = intval($val['status']);
            switch ($val['status']) {
                case 2:
                    $val['color'] = '#F00';
                    break;
                case 0:
                    $val['color'] = '#2F4F4F';
                    break;
                default:
                    $val['color'] = '#36C';
                    break;
            }
        }
    }

}

?>
